// 多选组控件
;(function($) {
	var myCheckbox =function(wrapper,options){
		options = options || {};
		this.options = $.extend({
			data: [],
			ids: [],
			indexs: [],
			onSelect:function(){},
		}, options);
		this.wrapper = wrapper;
		this.options.ids = this.options.ids ? this.options.ids : [];
		this.options.indexs = this.options.indexs ? this.options.indexs : [];
		this.checkIcon = '&#xe6d6;';
		this.unCheckIcon = '&#xe6d5;';
		this.init();
	}

	myCheckbox.prototype = {
		init:function(){
			this.wrapper.empty();
			this.wrapper.html(this.getHtml());
			this.bindEvents();
		},
		getHtml:function(){
			// 设置默认值
			var defaultDataList = [];
			if(this.options.ids.length > 0){
				defaultDataList = _.filter(this.options.data, function(item) {
					return _.contains(this.options.ids, item.id);
				}.bind(this)) || defaultData;
			}else if(this.options.indexs){
				defaultDataList = _.map(this.options.indexs, function(item) {
					return this.options.data && this.options.data[item];
				}.bind(this)) || defaultData;
			}
			this.wrapper.attr('value', _.pluck(defaultDataList,'id').join(',')).attr('title', _.pluck(defaultDataList,'title').join(','));
			var html ='';
			this.options.data.map(function(item){
				if(_.findWhere(defaultDataList,{id:item.id})){
					html+='<span value="'+item.id+'" class="checked"><i class="ttlofont ttl-anim">'+this.checkIcon+'</i><em>'+item.title+'</em></span>';
				}else{
					html+='<span value="'+item.id+'"><i value="'+item.id+'" class="ttlofont ttl-anim">'+this.unCheckIcon+'</i><em>'+item.title+'</em></span>';
				}
			}.bind(this))
			return html;
		},
		selectItemMult:function($tar){
			var param ={
				state:null,
				item:{
					id: $tar.attr('value'),
					title: $tar.find('em').text()
				}
			}
			if($tar.hasClass('checked')){
				// 取消选择
				$tar.removeClass('checked');
				$tar.find('i').html(this.unCheckIcon).removeClass('ttl-anim-scaleSpring');			
				param.state=0;
			}else{
				// 选择
				$tar.addClass('checked');
				$tar.find('i').html(this.checkIcon).addClass('ttl-anim-scaleSpring');	
				param.state=1;
			}
			var valueList=[],titleList=[];
			this.wrapper.find('span').map(function(ix,item){
				var $item = $(item);
				if($item.hasClass('checked')){
					valueList.push($item.attr('value'));
					titleList.push($item.find('em').text());
				}
			});
			this.wrapper.attr('value', valueList.join(',')).attr('title', titleList.join(','));
			this.options.onSelect(param);

		},
		bindEvents:function(){
			this.wrapper.bind('click',function(e){
				var $tar = $(e.target || e.srcElement);
				if($tar.closest('span').length){
					this.selectItemMult($tar.closest('span'));
				}
			}.bind(this));
		}
	}

	$.fn.uiCheckbox = function(options) {
		new myCheckbox(this, options);
	};
})(jQuery)